package com.atguigu.flink.chapter02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2023/6/16 10:07
 */
public class WcUnBounded {
    public static void main(String[] args) throws Exception {
    
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 1. 获取一个流的执行环境
        env.setParallelism(3);
        // 2. 通过执行环境,从 source 读取数据,到一个流
        DataStreamSource<String> fileStream = env.socketTextStream("hadoop162", 8888);
        // 3. 对流做各种转换
        // 3.1 对每行数据做切割
        SingleOutputStreamOperator<String> wordStream = fileStream.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, // 读取到每行数据
                                Collector<String> out) throws Exception {
                String[] words = line.split(" ");  // hello world
    
                for (String word : words) {
                    out.collect(word);
                    
                }
            }
        });
        // 3.2 给每个单词配置 1
        SingleOutputStreamOperator<Tuple2<String, Long>> wordOneStream = wordStream.map(new MapFunction<String, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(String word) throws Exception {
                return Tuple2.of(word, 1L);
            }
        
        });
        
        // 3. 按照单词分组.
        KeyedStream<Tuple2<String, Long>, String> keyedStream = wordOneStream.keyBy(new KeySelector<Tuple2<String, Long>, String>() {
            @Override
            public String getKey(Tuple2<String, Long> t) throws Exception {
                return t.f0;
            }
        });
        
        // 3. 按照分组聚合: 前面是元组,1 表示元组位置为 1 的元素进行聚合
        SingleOutputStreamOperator<Tuple2<String, Long>> result = keyedStream.sum(1).setParallelism(4);
    
        // 4. 输出结果
        result.print();
        
        // 4. 启动流的执行环境
        env.execute();
    }
}
